//
//  Util.swift
//  DLuxTravel
//
//  Created by 陆涛 on 2018/10/8.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit
import CoreLocation
import MapKit

class Util: NSObject {
    
    /// 是否有刘海屏
    @objc static var isNotch:Bool {
        
        guard #available(iOS 11.0, *) else {
            
            return false
        }
        let inset = UIApplication.shared.windows[0].safeAreaInsets
        
        return inset.bottom > 0
    }
    
    /// 打电话
    ///
    /// - Parameter tel: 电话号码
    class func phoneAction(tel:String) {
        
        let tel = tel.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).replacingOccurrences(of: " ", with: "")
        
        if let url = URL(string: "tel://\(tel)") {
            
            if UIApplication.shared.canOpenURL(url) {
                
                UIApplication.shared.openURL(url)
            }
        }
    }
    
    
    /// 打开网址
    ///
    /// - Parameter website: 网址
    class func websiteAction(website:String) {
        
        var website = website.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        
        if website.count == 0 {
            
            return
        }
        
        if !website.hasPrefix("http") {
            
            website = "http://\(website)"
        }
        
        if let url = URL(string: website) {
            
            if UIApplication.shared.canOpenURL(url) {
                
                UIApplication.shared.openURL(url)
            }
        }
    }
    
    
    /// 打开email
    ///
    /// - Parameter email: email
    class func emailAction(email:String) {
        
        let email = email.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).replacingOccurrences(of: " ", with: "")
        
        if let url = URL(string: "mailto:\(email)") {
            
            if UIApplication.shared.canOpenURL(url) {
                
                UIApplication.shared.openURL(url)
            }
        }
    }
    
    
    /// 打开外部地图
    ///
    /// - Parameters:
    ///   - to: 目的地坐标
    ///   - vc: 当前vc
    class func tractfic(to:CLLocationCoordinate2D,vc:UIViewController) {
        
        let useablemaps = useableMaps()
        let appname =  Bundle.main.infoDictionary?["CFBundleDisplayName"] ?? "ImGuiderX"
        let urlScheme = "imguiderx://"
        
        let alertVC = UIAlertController(title: nil, message: nil
            , preferredStyle: .actionSheet)
        
        useablemaps.forEach { info in
            
            let mapname = info["name"]
            let action = UIAlertAction(title: mapname as? String, style: .default) { _ in
                
                let tag = info["tag"] as! Int
                
                switch tag {
                    
                case 0 :// 苹果地图
                    
                    let fromLocation = MKMapItem.forCurrentLocation()
                    let toLocation = MKMapItem(placemark: MKPlacemark(coordinate: to, addressDictionary: nil))
                    MKMapItem.openMaps(with: [fromLocation,toLocation], launchOptions: [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey:NSNumber(booleanLiteral: true)])
                case 1://百度地图
                    
                    let urlstr = "baidumap://map/direction?origin={{我的位置}}&destination=latlng:\(to.latitude),\(to.longitude)|name=目的地&mode=driving&coord_type=gcj02".trimmingCharacters(in: CharacterSet.urlQueryAllowed)
                    
                    UIApplication.shared.openURL(URL(string: urlstr)!)
                    
                case 2://谷歌地图
                    
                    let urlstr = "comgooglemaps://?x-source=\(appname)&x-success=\(urlScheme)&saddr=&daddr=\(to.latitude),\(to.longitude)&directionsmode=driving".trimmingCharacters(in: CharacterSet.urlQueryAllowed)
                    
                    UIApplication.shared.openURL(URL(string: urlstr)!)
                case 3://高德地图
                    
                    let urlstr = "iosamap://navi?sourceApplication=\(appname)&backScheme=\(urlScheme)&lat=\(to.latitude)&lon=\(to.longitude)&dev=0&style=2".trimmingCharacters(in: CharacterSet.urlQueryAllowed)
                    
                    UIApplication.shared.openURL(URL(string: urlstr)!)
                default:
                    
                    return
                }
            }
            
            alertVC.addAction(action)
            
            alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
            
            if let popover = alertVC.popoverPresentationController {
                
                popover.sourceView = vc.view
                popover.sourceRect = vc.view.bounds
                popover.permittedArrowDirections = .any
            }
            
            vc.present(alertVC, animated: true, completion: nil)
        }
    }
    
    private class func useableMaps() -> [[String:Any]] {
        
        let allmaps = [["name":"苹果地图","url":"","tag":0],
                       ["name":"百度地图","url":"baidumap://","tag":1],
                       ["name":"谷歌地图","url":"comgooglemaps://","tag":2],
                       ["name":"高德地图","url":"iosamap://","tag":3]]
        
        
        return allmaps.filter { info -> Bool in
            
            if let urlstr = info["url"] as? String,urlstr.count > 0,let url = URL(string: urlstr) {
                
                if !UIApplication.shared.canOpenURL(url) {
                    
                    return false
                }
            }
            
            return true
        }
    }
}

extension Util {
    
    
    /// 获取顶层view controller
    ///
    /// - Parameter viewController: 当前view controller
    /// - Returns: 顶层view controller
    class func topViewController(_ viewController: UIViewController? = nil) -> UIViewController? {
        
        let viewController = viewController ?? UIApplication.shared.keyWindow?.rootViewController
        
        if let navigationController = viewController as? UINavigationController,
            !navigationController.viewControllers.isEmpty {
            
            return self.topViewController(navigationController.viewControllers.last)
        } else if let tabBarController = viewController as? UITabBarController,
            let selectedController = tabBarController.selectedViewController {
            
            return self.topViewController(selectedController)
        } else if let presentedController = viewController?.presentedViewController {
            
            return self.topViewController(presentedController)
        }
        
        return viewController
    }
}





